window.MapContextMenu = function(map,items){
	this.map = map;
	this.items = [];
	this.init(items);
}

window.MapContextMenu.prototype = {
	init : function(items){
		var me = this;
		this.parentId = this.map.getDiv().id;
		this.id = "mapContextMenu";
		this.creatRootDiv();
		for (var i = 0; items&&i < items.length; i++) {
			this.addItem(items[i].name,items[i].callback);
		}
		google.maps.event.addListener(this.map, 'rightclick', function(e) {
		    me.show(e);
		  });
	},
	
	creatRootDiv : function(){
		var root = this.rootDiv = $("<div>");
		root.attr("id",this.id);
		root.css("display","none");	
		root.css("position","absolute");
		var me = this;
		root.appendTo($("#"+this.parentId));
		$("body").click(function(){
			me.hide();
		});    
	},
	addItem:function(name,callback,imagepath){
		var me = this;
		var item = $("<div>").html(name);
		item.attr("id",this.rootDiv.attr("id")+this.items.length);
		item.addClass("mapContextMenuItem");
		if(imagepath){
			item.css("background-image","url("+imagepath+")");
		}
		item.click(function(){
			callback.apply(this,[me]);
		});
		item.appendTo(this.rootDiv);
		this.items.push(item);
	},
	
	show : function(e){
		this.popupLocation = e.latLng;
		var xy = e.pixel;		
		this.rootDiv.css("z-index",10);
		xy = this.getSuitePosition(xy);
		this.rootDiv.css("top",xy.y);
		this.rootDiv.css("left",xy.x);
		this.rootDiv.css("display","block");
	},
	
	hide : function(){
		if(this.rootDiv){
			this.rootDiv.css("display","none");
		}
	},
	
	getSuitePosition:function(xy){
		var width = this.rootDiv.width();
		var parentWidth = $("#"+this.parentId).width();
		if(xy.x+width>parentWidth){
			xy.x = xy.x-width;
		}
		
		var height = this.rootDiv.height();
		var parentHeight = $("#"+this.parentId).height();
		if(xy.y+height>parentHeight){
			xy.y = xy.y-height;
		}
		return xy;
	}
}